<template>
  <basic-container>
    <div class="header">
      <!--日期与模板-->
      <div class="header-up">
        <div class="date-template">
          <div class="dt-item">
            <el-date-picker
              size="mini"
              v-model="queryDate"
              type="daterange"
              align="right"
              unlink-panels
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              :clearable="false"
              @change="dateChange">
            </el-date-picker>
          </div>
          <div class="dt-item">
            <el-button size="mini" type="primary" @click="changeDateModel">切换日期样式</el-button>
          </div>
          <div class="dt-item">
            <el-button size="mini" type="primary" @click="changeDefualtTemplate">默认模板</el-button>
          </div>
          <div class="dt-item">
            <el-select v-model="templateSelect" placeholder="请选择模板" style="width: 125px; margin-right: 5px" size="mini"
                       @change="templateChange">
              <el-option
                v-for="item in templateList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">
                    <el-button size="mini" @click.stop="deleteTemplate(item.id, item.name)" type="text"><i
                      class="el-icon-delete"/></el-button>
                  </span>
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="yesterday">昨日数据已更新至时区:{{ timezone }}</div>
      </div>
      <!--筛选条件-->
      <cs-filter-query ref="csFilterQueryRef" :options="filterQueryOptions"
                       @change="handleChangeFilter"></cs-filter-query>
    </div>
    <div class="data-report">
      <div class="curd-table">
        <div class="tab-header clearfix">
          <div class="tab-header-left" style="line-height: 32px;font-size: 12px;"  v-if="isDateModel">
            订单消耗总和：{{ countTotalCost() }}
          </div>
          <div class="tab-header-right">
            <el-tooltip class="item" effect="dark" content="清空" placement="top">
              <el-button icon="el-icon-delete" size="mini" circle @click="$refs.csFilterQueryRef.clear()"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="保存模板" placement="top">
              <el-button icon="myicon icon-save" size="mini" circle @click="handleModelOpen"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="导出" placement="top">
              <el-button icon="el-icon-download" size="mini" circle @click="excelExport"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="显隐" placement="top">
              <el-button icon="el-icon-s-operation" size="mini" circle @click="tableColumnDrawer = true"></el-button>
            </el-tooltip>
          </div>
        </div>
        <div class="table-body">
          <el-table
            v-loading="loading"
            :data="tableData"
            border
            :show-summary="true"
            :summary-method="getSummaries"
            :header-cell-style="iHeaderCellStyle"
            :cell-style="iCellStyle"
            style="width: 100%"
            @sort-change="sortTableData">
            <el-table-column
              v-for="item in renderTableColumn"
              :prop="item.value"
              :label="item.label"
              min-width="90"
              :sortable="item.sortable"
              :width="item.width?item.width:''"
              :fixed="item.fixed">
              <template
                slot="header"
                slot-scope="scope"
              >
                <span v-show="scope.column.label === '合计'">
                    <el-tooltip placement="top">
                      <div slot="content">
                        <span>所选日期范围的合计值</span>
                      </div>
                      <i class="el-icon-warning" style="color:#409EFF; margin-right:5px;"></i>
                    </el-tooltip>
                  </span>
                <span v-show="scope.column.label === '本月合计'">
                    <el-tooltip placement="top">
                      <div slot="content">
                        <span>当月的合计，与所选日期无关</span>
                      </div>
                      <i class="el-icon-warning" style="color:#409EFF; margin-right:5px;"></i>
                    </el-tooltip>
                  </span>
                <span v-show="scope.column.label === '本月预估'">
                    <el-tooltip placement="top">
                      <div slot="content">
                        <span>取当月靠前十天的数据÷10×当月天数，与所选日期无关</span>
                      </div>
                      <i class="el-icon-warning" style="color:#409EFF; margin-right:5px;"></i>
                    </el-tooltip>
                  </span>
                <span>{{ scope.column.label }}</span>
              </template>
              <template v-slot="{ row }" v-if="item.value==='offerName'">
                <a href="javascript:void(0)" @click="openOcPage(row.offerId,'offer')">{{ row.offerName }}</a>
              </template>
              <template v-slot="{ row }" v-else-if="item.value==='platformId'">
                <a href="javascript:void(0)" @click="openOcDataReport(row,'offer')">{{ row.platformId }}</a>
              </template>
              <template v-slot="{ row }" v-else-if="item.value==='customerName'">
                <a href="javascript:void(0)" @click="gotoOffer(row.offerId)">{{ row.customerName }}</a>
              </template>
              <template v-slot="{ row }" v-else-if="item.value==='accountName'">
                <a href="javascript:void(0)" @click="gotoAccount(row.accountName)">{{ row.accountName }}</a>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="bottom-page clearfix">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.current"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size="page.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
      <el-drawer
        title="列显隐"
        size="800px"
        :visible.sync="tableColumnDrawer"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        :append-to-body="true"
        :wrapperClosable="false"
      >
        <el-divider></el-divider>
        <cs-drawer-container>
          <!--<div class="drawer-box">-->
          <!--  <draggable v-model="tableHeaderOpt" chosenClass="chosen" forceFallback="true" group="people" animation="100"-->
          <!--             @start="onStart" @end="onEnd">-->
          <!--    <transition-group>-->
          <!--      <div class="drag-box" v-for="item in tableHeaderOpt" :key="item.value">-->
          <!--        <el-checkbox v-model="item.check"-->
          <!--                     :disabled="item.value ==='cost'">{{ item.label }}-->
          <!--        </el-checkbox>-->
          <!--        <i class="el-icon-s-fold"></i>-->
          <!--      </div>-->
          <!--    </transition-group>-->
          <!--  </draggable>-->
          <!--</div>-->
          <div class="drawer-box">
            <div class="drawer-box-left">
              <div class="drawer-box-left-input">
                <el-input v-model="headerQueryIntputLeft" size="mini" prefix-icon="el-icon-search"
                          placeholder="请输入搜索内容" clearable></el-input>
              </div>
              <div class="drawer-box-left-tab">
                <el-tabs type="border-card">
                  <el-tab-pane label="维度">
                    <el-checkbox-group v-model="checkedDimCol">
                      <el-checkbox v-for="item in dimSearchData" :label="item.value" :key="item.value"
                                   :disabled="item.disabled"
                                   @change="handleCheckedDimCol($event,item)">{{ item.label }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
            <div class="drawer-box-right">
              <el-input v-model="headerQueryIntputRight" size="mini" prefix-icon="el-icon-search"
                        placeholder="请输入搜索内容" clearable></el-input>
              <div class="select-label">已选{{ tableHeaderOpt.length }}列</div>
              <draggable v-model="tableHeaderOpt" chosenClass="chosen" forceFallback="true" group="people"
                         filter=".forbid"
                         animation="100"
                         :move="onMove">
                <transition-group>
                  <div :class="isDisabled(item.value)?'drag-box forbid':'drag-box'"
                       v-for="item in rightSearchData" :key="item.value">
                    <div class="drag-box-left">
                      <i class="myicon icon-igw-l-menu-2"></i>
                      <span>{{ item.label }}</span>
                    </div>
                    <div class="drag-box-right" v-show="!isDisabled(item.value)">
                      <i class="myicon icon-zhiding" @click="upCheckedCol(item)"></i>
                      <i class="myicon icon-cha" @click="removeCheckedCol(item)"></i>
                    </div>
                  </div>
                </transition-group>
              </draggable>
            </div>
          </div>
          <el-button slot="bottom" size="mini" type="primary" @click="createReport">生成报告</el-button>
        </cs-drawer-container>
      </el-drawer>
    </div>
    <el-dialog :visible.sync="saveDialog" append-to-body width="30%"
               :close-on-click-modal="false" :show-close="false">
      <div>
        <el-form ref="modelFormRef" :model="modelForm" :rules="modelRules"
                 style="margin: 0 auto;width: 80%;text-align: center">
          <el-form-item prop="modelFormat">
            <el-radio-group v-model="modelForm.modelFormat">
              <el-radio label="0" @change="setTemplateName(true)">
                保存为新模板
              </el-radio>
              <el-radio label="1" @change="setTemplateName(false)" :disabled="templateList.length === 0">覆盖当前的模板
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="modelName" label="模板名：" style="position: relative">
            <el-input size="mini" placeholder="请输入模板名称" v-model="modelForm.modelName"/>
            <span v-if="modelForm.modelFormat === '1'"
                  style="color: #f56c6c; position: absolute; left: 0; top: 86px; width: 200px; text-align: left; font-size: 12px">您可以对现有模板重命名</span>
          </el-form-item>
          <el-form-item style="margin-top: 45px">
            <el-button type="primary" size="mini" @click="saveModel" :disabled="saveTemplateloading">确定</el-button>
            <el-button size="mini" @click="saveDialog = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import CsFilterQuery from "@/components/CsFilterQuery/CsFilterQuery";
import baseQueryList from "@/mixins/base-query-list";
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import {
  excelExport, getAccount, getCustomer, getCustomerManager, getOffer, getOperator,
  getOwnTemplate, getSalesManager, removeTemplateByids, saveUpdateTemplate,
  statisticsCostReportByDateHorizontal,
  statisticsCostReportByDateVertical, statisticsCostReportByDateVerticalTotal,statisticsCostReportByDateVerticalTotalDefault
} from "@/api/dataReport/cost-report-new";
import Moment from "moment";
import {getDictList, getSysDictList} from "@/api/system/dict";
import draggable from "vuedraggable"
import {columnTip} from "@/util/util";
import _ from "lodash";
import website from "@/config/website";
import {getToken} from "@/util/auth";
import {genTokenKey} from "@/api/user";
import {OC_LOGIN_URL} from "@/const/urlConst";

export default {
  name: "CostReportNew",
  mixins: [baseQueryList],
  components: {
    CsFilterQuery,
    CsDrawerContainer,
    draggable
  },
  data() {
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    const that = this
    return {
      pickerOptions: {
        onPick({minDate, maxDate}) {
          if (minDate) {
            that.pickerMinDate = minDate.getTime()
          }
          if (maxDate) {
            that.pickerMinDate = 0
          }
        },
        disabledDate(time) {
          if (that.pickerMinDate !== 0) {
            return (
              that.pickerMinDate - 3600 * 1000 * 24 * 92 > time.getTime() ||
              that.pickerMinDate + 3600 * 1000 * 24 * 92 < time.getTime() ||
              time.getTime() > Date.now()
            )
          } else {
            return time.getTime() > Date.now();
          }
        }
      },
      // 查询日期范围
      queryDate: [Moment(start).format('YYYY-MM-DD'), Moment(end).format('YYYY-MM-DD')],
      // 模板
      currentTemplate: '0',
      loading: false,
      // 表格数据
      tableData: [],
      page: {
        current: 1,
        size: 10,
      },
      total: 0,
      // 显隐弹窗
      tableColumnDrawer: false,
      // 显隐已选择项
      tableColumnValue: [],
      // 显隐配置项
      tableColumnData: [],
      // 过滤参数
      filterQueryInfo: {},
      // 表格头部配置
      tableHeaderOpt: [],
      // 侧边显影数值
      checked: true,
      // 切换日期显示
      isDateModel: false,
      // 时区
      timezone: '',
      // 花费统计
      costTotal: '',
      // 订单
      offerList: [],
      // 客户经理列表
      customerManagerList: [],
      // 客户列表，
      customerList: [],
      // 账户列表
      accountList: [],
      // 账户运营人列表
      operatorList: [],
      // 销售经理列表
      salesManagerList: [],
      //默认模版合计
      defaultCost:[],
      // 模板列表
      templateList: [],
      templateSelect: '',
      templateSelectOld: '',
      templateDefaultName: '',
      saveDialog: false,
      modelForm: {
        modelFormat: '0',
        modelName: '',
      },
      modelRules: {
        modelFormat: [{required: true, message: '请选择模板保存形式', trigger: 'change'}],
        modelName: [{required: true, message: '请输入模板名称', trigger: 'blur'},
          {min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur'}]
      },
      saveTemplateloading: false,
      drag: false,
      // 固定表头
      fixed: ["offerName", "platformId", "customerName", "platform", "operatorName", "salesManagerName", "customerManagerName", "totalCost", "monthSum", "monthExpectedSum", "lastMonthSum"],
      // 左对齐的表头
      alignLeftHeader: ["offerName", "platformId", "customerName", "platform", "operatorName", "salesManagerName", "customerManagerName"],
      // 排序
      sortList: [],
      // 自定义列搜索
      headerQueryIntputLeft: '',
      headerQueryIntputRight: '',
      checkedDimCol: [],
      // 维度参数
      dimColList: [
        {
          value: "cost",
          label: "花费",
          disabled: true,
          check: true
        },
        {
          value: "offerName",
          label: "订单",
          check: true
        },
        {
          value: "platform",
          label: "媒体",
          check: false
        },
        {
          value: "operatorName",
          label: "账户运营人",
          check: false
        },
        {
          value: "platformId",
          label: "账户ID",
          check: false
        },
        {
          value: "accountName",
          label: "账户名称",
          check: false
        },
        {
          value: "agencyName",
          label: "代理",
          check: true
        },
        {
          value: "customerName",
          label: "客户",
          check: false
        },
        {
          value: "salesManagerName",
          label: "销售经理",
          check: false
        },
        {
          value: "customerManagerName",
          label: "客户经理",
          check: false
        }, {
          value: "totalCost",
          label: "合计",
          check: true
        },
        {
          value: "monthSum",
          label: "本月合计",
          check: true
        },
        {
          value: "monthExpectedSum",
          label: "本月预估",
          check: true
        },
        {
          value: "lastMonthSum",
          label: "上月合计",
          check: true
        },
        {
          value: "timeZoneStr",
          label: "时区",
          check: false
        }
      ],
      groupListIgnore: [],
      // 代理选择
      agencyNameList: []
    }
  },
  computed: {
    // 媒体列表
    translatePlatformList() {
      return this.platformList.map(item => {
        return {
          label: item.dictValue,
          value: item.dictKey
        }
      })
    },
    // 查询表头
    groupList() {
      return this.tableHeaderOpt.filter(item => !this.groupListIgnore.includes(item.value)).map(item => item.value).join(',')
    },
    // 筛选组件配置
    filterQueryOptions() {
      return [{
        value: 'platform',
        label: '媒体',
        children: this.translatePlatformList
      }, {
        value: 'offerId',
        label: '订单',
        queryList: this.offerList
      }, {
        value: 'customerId',
        label: '客户',
        queryList: this.customerList
      }, {
        value: 'platformId',
        label: '账户ID',
        queryList: this.accountList
      }, {
        value: 'operatorId',
        label: '账户运营人',
        queryList: this.operatorList
      }, {
        value: 'salesManagerId',
        label: '销售经理',
        queryList: this.salesManagerList
      }, {
        value: 'customerManagerId',
        label: '客户经理',
        queryList: this.customerManagerList
      }, {
        value: 'agencyName',
        label: '代理',
        children: this.agencyNameList
      }]
    },
    renderTableColumn() {
      return this.tableColumnData.filter(item => this.tableColumnValue.includes(item.value))
    },
    // 维度搜索
    dimSearchData() {
      if (this.headerQueryIntputLeft) {
        return this.dimColList.filter(item => {
          const input = this.headerQueryIntputLeft.toLowerCase()
          const label = item.label.toLowerCase()
          return label.includes(input)
        })
      } else {
        return this.dimColList
      }
    },
    // 右边搜索栏
    rightSearchData() {
      if (this.headerQueryIntputRight) {
        return this.tableHeaderOpt.filter(item => {
          const input = this.headerQueryIntputRight.toLowerCase()
          const label = item.label.toLowerCase()
          return label.includes(input)
        })
      } else {
        return this.tableHeaderOpt
      }
    },
  },
  watch: {},
  async created() {
    this.initHeaderCol()
    await this.getTemplateList()
    // debugger
    if (this.templateList.length > 0) {
      this.tableHeaderOpt = this.handleGroupList(this.templateList[0].groupData)
      this.checkedDimCol = this.templateList[0].groupData.split(',')
      this.templateSelect = this.templateList[0].id
      this.templateSelectOld = this.templateList[0].id
      this.filterQueryInfo = JSON.parse(this.templateList[0].filterData)
    }
    await this.getData()
    this.getTimezone()
    this.getOfferList()
    this.getCustomerManagerList()
    this.getCustomerList()
    this.getAccountList()
    this.getOperatorList()
    this.getSalesManagerList()
    this.getAgencyNameList()
  },
  methods: {
    iHeaderCellStyle({row, column, rowIndex, columnIndex}) {
      if (this.alignLeftHeader.includes(column.property)) {
        return {
          textAlign: 'left',
          color: '#101010',
          backgroundColor: '#F2F2F2',
        }
      } else {
        return {
          textAlign: 'right',
          color: '#101010',
          backgroundColor: '#F2F2F2',
        }
      }
    },
    iCellStyle({row, column, rowIndex, columnIndex}) {
      if (this.alignLeftHeader.includes(column.property)) {
        return {
          textAlign: 'left',
        }
      } else {
        return {
          textAlign: 'right',
        }
      }

    },
    handleSizeChange(val) {
      this.page.size = val
      this.page.current = 1
      this.getData()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.getData()
    },
    // 获取模板列表
    async getTemplateList() {
      const {data: res} = await getOwnTemplate()
      if (res.code !== 200) return
      this.templateList = res.data
    },
    dateChange() {
      //重新选择日期，排序重置
      this.sortList = [];
      this.getData();
    },
    //
    async getData() {
      if (!this.queryDate) return
      const params = {
        ...this.page,
      }
      const data = {
        ...this.filterQueryInfo,
        groupList: this.groupList,
        startDate: this.queryDate[0],
        endDate: this.queryDate[1],
        orderList: JSON.stringify(this.sortList)
      }
      if (this.templateSelect !== '') {
        data.tempId = this.templateSelect
      }
      let res
      this.loading = true
      if (this.isDateModel) {
        res = await statisticsCostReportByDateVertical(params, data).finally(() => {
          this.loading = false
        })
        const {data: {data: summary}} = await statisticsCostReportByDateVerticalTotal(params, data).finally(() => {
          this.loading = false
        })
        this.costTotal = summary.cost
      } else {
        res = await statisticsCostReportByDateHorizontal(params, data).finally(() => {
          this.loading = false
        })
        //默认合计
        const {data: {data: summary}} = await statisticsCostReportByDateVerticalTotalDefault(params, data).finally(() => {
          this.loading = false
        })
        console.log(summary)
        this.defaultCost = summary
      }
      this.tableData = res.data.data.records
      this.total = res.data.data.total
      this.tableColumnData = res.data.data.header.map(item => {
        item.fixed = this.fixed.includes(item.value)
        if (item.value === 'customerName') {
          item.width = 150
        }
        if (item.sortable) {
          item.sortable = 'custom'
        }
        return item
      })
      const hideCol = this.groupListIgnore.filter(item => this.tableHeaderOpt.some(() => {
      }))
      this.tableColumnValue = res.data.data.header.map(item => item.value)
    },
    // 筛选框查询
    handleChangeFilter(val) {
      this.filterQueryInfo = val
      this.page.current = 1;
      this.getData()
    },
    // 侧边生成报告
    createReport() {
      if (this.tableHeaderOpt.filter(item => item.check).length < 2) return this.$message.error('请选择至少一个条件列')
      this.tableColumnDrawer = false
      this.getData()
    },
    // 改变日期模式
    changeDateModel() {
      this.isDateModel = !this.isDateModel
      this.page.current = 1
      this.getData()
    },
    // 获取时区
    async getTimezone() {
      const {timezone} = await getSysDictList('timezone')
      let timezoneList = timezone;
      let currentTimezoneOfUpdateData = 2 - (new Date()).getUTCHours();
      if (currentTimezoneOfUpdateData > 12) {
        currentTimezoneOfUpdateData -= 24;
      }
      if (currentTimezoneOfUpdateData < -12) {
        currentTimezoneOfUpdateData += 24;
      }
      timezoneList.map(item => {
        if (currentTimezoneOfUpdateData == item.dictValue) {
          this.timezone = item.dictKey
        }
      })
    },
    // 导出报告
    async excelExport() {
      const res = await excelExport({}, {
        groupList: this.groupList,
        startDate: this.queryDate[0],
        endDate: this.queryDate[1],
        ...this.filterQueryInfo,
      })
      let filename = window.decodeURI(res.headers['content-disposition'].split('=')[1])
      let url = window.URL.createObjectURL(new Blob([res.data]))
      let link = document.createElement("a")
      link.style.display = "none"
      link.href = url
      link.download = filename
      document.body.appendChild(link)
      link.click()
    },
    // 合计方法
    getSummaries({columns, data}) {
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if(this.isDateModel){
          if (column.property === 'cost') {
            sums[index] = this.costTotal
          } else {
            sums[index] = ''
          }
        }else {
          const values = this.defaultCost.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value)) && !['agencyName','platform','platformId'].includes(column.property)) {
            sums[index] = values.reduce((prev, curr) => {
              const value = curr;
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, '');
          } else {
            sums[index] = '';
          }
        }

      });
      return sums
    },
    // 保存模板
    // async saveTemplate() {
    //   const data = {
    //     groupData: this.checkList.join(',')
    //   }
    //   if (this.currentTemplate !=='0') {
    //     data.id = this.currentTemplate
    //   }
    //   const {data: res} = await saveUpdateTemplate(data)
    //   await this.getTemplateList()
    //   // console.log(res)
    // },
    // 改变模板
    // handleChangeTemplate(val) {
    //   if (val === '0') {
    //     this.checkList = ["offerName"]
    //   } else {
    //     const template = this.templateList.find(item => item.id === val).groupData.split(',')
    //     this.checkList = template
    //   }
    //   this.getData()
    // },
    // 获取订单
    async getOfferList() {
      const {data: res} = await getOffer()
      this.offerList = res.data.map(item => {
        return {
          value: item.key,
          label: item.name
        }
      })
    },
    // 获取客户经理
    async getCustomerManagerList() {
      const {data: res} = await getCustomerManager()
      this.customerManagerList = res.data.map(item => {
        return {
          value: item.key,
          label: item.name
        }
      })
    },
    // 获取客户
    async getCustomerList() {
      const {data: res} = await getCustomer()
      this.customerList = res.data.map(item => {
        return {
          value: item.key,
          label: item.name
        }
      })
    },
    // 获取账户
    async getAccountList() {
      const {data: res} = await getAccount()
      this.accountList = res.data.map(item => {
        return {
          value: item.key,
          label: item.name
        }
      })
    },
    // 获取运营人
    async getOperatorList() {
      const {data: res} = await getOperator()
      this.operatorList = res.data.map(item => {
        return {
          value: item.key,
          label: item.name
        }
      })
    },
    // 获取销售经理
    async getSalesManagerList() {
      const {data: res} = await getSalesManager()
      this.salesManagerList = res.data.map(item => {
        return {
          value: item.key,
          label: item.name
        }
      })
    },
    async delTemplate(id) {
      const temp = this.currentTemplate
      const {data: res} = await removeTemplateByids(id)
      if (res.code !== 200) return
      // console.log(id,temp)
      if (id === temp) {
        this.currentTemplate = '0'
      } else {
        this.currentTemplate = temp
      }
      await this.getTemplateList()
      // console.log(res)
    },
    //
    handleModelClose() {
      this.saveDialog = false
      this.getTemplateList()
    },
    handleModelOpen() {
      this.saveDialog = true
      // 设置默认模板名
      this.templateDefaultName = '自定义模板'
      if (this.templateSelect && !isNaN(this.templateSelect)) {
        this.modelForm.modelFormat = '1'
        this.setTemplateName(false)
      } else {
        this.modelForm.modelFormat = '0'
        this.setTemplateName(true)
      }
    },
    findTemplateByName(name) {
      for (let i = 0; i < this.templateList.length; i++) {
        if (this.templateList[i].name === name) {
          return this.templateList[i].id
        }
      }
      return false
    },
    // 更换模板
    templateChange(val) {
      this.templateList.map(item => {
        if (item.id === val) {
          this.modelForm.modelFormat = '0'
          this.modelForm.modelName = this.templateDefaultName
          this.templateSelectOld = item.id
          this.tableHeaderOpt = this.handleGroupList(item.groupData)
          this.checkedDimCol = item.groupData.split(',')
          this.filterQueryInfo = JSON.parse(item.filterData)
        }
      })
      this.getData()
    },
    setTemplateName(flag) {
      if (flag) {
        this.modelForm.modelName = this.templateDefaultName
      } else {
        this.templateList.map(item => {
          if (item.id === this.templateSelectOld) {
            this.modelForm.modelName = item.name
          }
        })
      }
    },
    deleteTemplate(id, name) {
      this.$confirm("确定删除模板【" + name + "】?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        removeTemplateByids(id).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          })
          this.getTemplateList()
          this.templateSelect = null
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    /**
     * 保存模板
     */
    saveModel() {
      this.saveTemplateloading = true
      this.$refs.modelFormRef.validate(async valid => {
        if (valid) {
          let data = {
            groupData: this.groupList,
            name: this.modelForm.modelName,
            id: this.templateSelectOld,
            filterData: JSON.stringify(this.filterQueryInfo)
          }
          console.log(data)
          if (this.modelForm.modelFormat === '0') {
            let id = this.findTemplateByName(data.name)
            if (id) {
              this.$confirm('此模板名已经存在，是否要覆盖该模板？', '提示', {
                confirmButtonText: '覆盖',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(async () => {
                data.id = id
                await saveUpdateTemplate(data)
                await this.getTemplateList()
              })
            } else {
              delete data.id
              await saveUpdateTemplate(data)
              await this.getTemplateList()
            }
          } else if (this.modelForm.modelFormat === '1' && data.id) {
            await saveUpdateTemplate(data)
            await this.getTemplateList()
          } else {
            this.$message({
              type: "error",
              message: "当前未选择覆盖模板！"
            })
          }
          this.saveTemplateloading = false
          this.saveDialog = false
        } else {
          this.saveTemplateloading = false
        }
      })
    },
    // 切换默认模板
    changeDefualtTemplate() {
      const defaultValue = 'cost,offerName,totalCost,monthSum,monthExpectedSum,lastMonthSum'
      this.tableHeaderOpt = this.handleGroupList(defaultValue)
      this.checkedDimCol = defaultValue.split(',')
      this.templateSelect = ''
      this.filterQueryInfo = {}
      this.getData()
    },
    //开始拖拽事件
    onStart() {
      this.drag = true;
    },
    //拖拽结束事件
    onEnd() {
      this.drag = false;
    },
    // 处理侧边排序数组
    handleGroupList(groupList) {
      const opt = this.dimColList
      const checkList = groupList.split(',')
      return opt.filter(item => {
        return checkList.includes(item.value)
      })
    },
    // 排序
    sortTableData(val) {
      let prop = val.prop;
      let orderBy = null;
      if (val.order === "descending") {
        orderBy = 'desc';
        //向上排序
      } else if (val.order === "ascending") {
        orderBy = 'asc';
        //不排序
      }
      if (orderBy != null) {
        this.sortList = [{name: prop, orderBy: orderBy}];
      } else {
        this.sortList = [];
      }
      this.getData()
    },
    // 维度选择框事件
    handleCheckedDimCol(event, val) {
      if (event) {
        // 添加对象
        this.tableHeaderOpt.push(val)
      } else {
        // 删除对象
        this.tableHeaderOpt = _.remove(this.tableHeaderOpt, function (n) {
          // 数组中的对象
          return !_.isEqual(n, val) // 比较对象
        })
      }
    },
    //禁止拖动到id为1的对象
    onMove(e) {
      console.log(e.relatedContext.element.value)
      const dis = this.dimColList.filter(item => item.disabled).map(item => item.value)
      if (dis.includes(e.relatedContext.element.value)) return false;
      return true;
    },
    // 禁用的行
    isDisabled(value) {
      if (value === 'cost') {
        return true
      } else {
        return false
      }
    },
    // 移除已选择列
    removeCheckedCol(val) {
      this.tableHeaderOpt = _.remove(this.tableHeaderOpt, function (n) {
        // 数组中的对象
        return !_.isEqual(n, val) // 比较对象
      })
      this.checkedDimCol = _.remove(this.checkedDimCol, function (n) {
        // 数组中的对象
        return n !== val.value
      })
      this.checkedBaseTarget = _.remove(this.checkedBaseTarget, function (n) {
        // 数组中的对象
        return n !== val.value
      })
    },
    // 置顶已选择列
    upCheckedCol(val) {
      const dis = this.dimColList.filter(item => item.disabled)
      this.tableHeaderOpt = _.remove(this.tableHeaderOpt, function (n) {
        // 数组中的对象
        return !_.isEqual(n, val) // 比较对象
      })
      this.tableHeaderOpt.splice(dis.length, 0, val)
      // this.tableHeaderOpt.unshift(val)
    },
    // 初始化表头
    initHeaderCol() {
      this.tableHeaderOpt = [...this.dimColList.filter(item => item.check)]
      this.checkedDimCol = this.dimColList.filter(item => item.check).map(item => item.value)
      this.tableColumnData = [...this.tableHeaderOpt]
    },
    openOcPage(offerId, type) {
      let ocTokenKey = '';
      let headers = {};
      headers[website.tokenHeader] = getToken();
      genTokenKey({
        sync: true,
        headers: headers,
        info: this.getTokenKeyInfo(offerId, type),
        success: (data) => {
          ocTokenKey = data.tokenKey;
        },
        error: () => {
        }
      });
      if (ocTokenKey == '') {
        this.$message.error('获取信息错误，无法正确跳转到订单中心');
        return;
      }
      let eleList = document.querySelectorAll('div[newPageLink]');
      let content = eleList[0];
      let linkEle = document.createElement("a");
      content.appendChild(linkEle);

      // 利用URL.createObjectURL()方法为a元素生成blob URL
      linkEle.target = '_blank';
      linkEle.href = OC_LOGIN_URL + '?tokenKey=' + ocTokenKey;
      linkEle.click();
      linkEle.remove();
    },
    openOcDataReport(row, type) {
      let ocTokenKey = '';
      let headers = {};
      headers[website.tokenHeader] = getToken();
      genTokenKey({
        sync: true,
        headers: headers,
        info: this.getTokenKeyInfo(row.offerId, type),
        success: (data) => {
          ocTokenKey = data.tokenKey;
        },
        error: () => {
        }
      });
      if (ocTokenKey == '') {
        this.$message.error('获取信息错误，无法正确跳转到订单中心');
        return;
      }
      let eleList = document.querySelectorAll('div[newPageLink]');
      let content = eleList[0];
      let linkEle = document.createElement("a");
      content.appendChild(linkEle);

      // 利用URL.createObjectURL()方法为a元素生成blob URL
      linkEle.target = '_blank';
      linkEle.href = OC_LOGIN_URL + '?tokenKey=' + ocTokenKey + '&path=/dataReport_oc/index&query=' + JSON.stringify({platformId: row.platformId});
      linkEle.click();
      linkEle.remove();
    },
    gotoOffer(offerId) {
      this.$router.push({
        path: '/business/offer'
      })
      setTimeout(()=>{
        this.$bus.emit('getOfferId', offerId)
      },0)

    },
    gotoAccount(accountName) {
      this.$router.push({
        path: '/business/account'
      })
      setTimeout(()=>{
        this.$bus.emit('getAccount', accountName)
      },0)

    },
    getTokenKeyInfo(offerId, type) {
      if (type == 'offer') {
        return JSON.stringify({offerId: offerId});
      }
      return '';
    },
    async getAgencyNameList() {
      const {agency_list} = await getSysDictList('agency_list')
      this.agencyNameList = agency_list.map(item => {
        return {
          label: item.dictValue,
          value: item.dictValue
        }
      })
    },
    countTotalCost() {
      if (this.isDateModel) {
        return this.costTotal
      } else {
        const total = this.tableData.reduce((total, cur) => {
          return total + parseFloat(cur.totalCost)
        }, parseFloat('0.00'))
        return total.toFixed(2)
      }

    }
  }
}
</script>

<style lang="scss" scoped>
.header {

  .header-up {
    display: flex;
    justify-content: space-between;

    .date-template {
      .dt-item {
        display: inline-block;
        margin-bottom: 10px;
        margin-right: 10px;
      }
    }

    .yesterday {
      color: green;
    }
  }

}

.card-header {
  display: flex;
  justify-content: flex-end;
}

::v-deep .el-card__header {
  border-bottom: unset;
}

.curd-table {
  .tab-header {
    font-size: 14px;
    margin-bottom: 15px;

    .tab-header-left {
      float: left;

      & > * {
        margin-right: 15px;
      }
    }

    .tab-header-right {
      float: right;
    }
  }

  .bottom-page {
    height: 100px;
    margin-top: 15px;

    .el-pagination {
      float: right;
    }
  }

  ::v-deep .cell {
    overflow: hidden; //溢出内容隐藏
    text-overflow: ellipsis; //文本溢出部分用省略号表示
    display: -webkit-box; //特别显示模式
    -webkit-line-clamp: 2; //行数
    line-clamp: 2;
    -webkit-box-orient: vertical; //盒子中内容竖直排列
  }
}

.el-transfer {
  height: 100%;
  display: -webkit-box;

  /deep/ .el-transfer-panel {
    height: 100%;

    .el-transfer-panel__body {
      height: 100%;

      .el-transfer-panel__list {
        height: 100%;
      }
    }
  }
}

.clearfix:after {
  content: "";
  display: block;
  clear: both;
}

.el-checkbox-group {
  display: flex;
  flex-direction: column;
}

.drawer-box {
  padding: 0 15px;
  display: flex;
  justify-content: space-between;
  height: 100%;

  .el-input {
    ::v-deep .el-input__inner {
      border-radius: 15px;
    }
  }

  .drawer-box-left {
    border: 1px solid #E8E8E8;
    border-radius: 5px;
    flex: 1;
    margin-right: 15px;
    display: flex;
    flex-direction: column;

    .drawer-box-left-input {
      padding: 15px 20px;
    }

    .drawer-box-left-tab {
      flex: 1;

      .el-tabs {
        height: 100%;
        box-sizing: border-box;
        box-shadow: unset;
        border-bottom: unset;
        border-left: unset;
        border-right: unset;

        .el-checkbox-group {
          display: block;

          .el-checkbox {
            width: 25%;
          }
        }
      }
    }
  }

  //.drawer-box-right {
  //  width: 300px;
  //  border: 1px solid #E8E8E8;
  //  border-radius: 5px;
  //  padding: 15px 20px;
  //
  //  .select-label {
  //    line-height: 45px;
  //    height: 45px;
  //    font-size: 14px;
  //  }
  //}
  .drawer-box-right {
    width: 300px;
    border: 1px solid #E8E8E8;
    border-radius: 5px;
    padding: 15px 20px;
    display: flex;
    flex-direction: column;

    .select-label {
      line-height: 45px;
      height: 45px;
      font-size: 14px;
    }

    .tableHeaderOpt {
      flex: 1;
      overflow: auto;
    }
  }

  .drag-box {
    padding: 5px 0;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    cursor: move;

    .drag-box-left {
      color: #101010;
      font-size: 14px;

      i {
        margin-right: 18px;
      }
    }

    .drag-box-right {
      i {
        cursor: pointer;

        &:first-child {
          margin-right: 18px;
        }
      }
    }
  }
}

.forbid {
  cursor: default !important;
}
</style>
